package com.huangsm.book.designmodel.parallel.masterworker;

import java.util.Map;
import java.util.Queue;

/**
 * @author huang
 * @PACKAGE_NAME com.huangsm.book.designmodel.parallel.masterworker
 * @PROJECT_NAME concurrence
 * @date 2019/2/19
 */
public class Worker implements Runnable {
    /**
     *任务队列，用于获取子任务
     */
    private Queue<Object> workQueue;

    /**
     * 子任务处理结果集
     */
    protected Map<String,Object> resultMap;

    public void setWorkQueue(Queue<Object> workQueue) {
        this.workQueue = workQueue;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    /**
     * 子任务处理逻辑
     * @param input
     * @return
     */
    public Object handle(Object input){
        return input;
    }
    @Override
    public void run() {
        while (true){
            //获取子任务
            Object input = workQueue.poll();
            if (input==null)break;
            //处理子任务
            Object handle = handle(input);
            //将处理结果写入结果集
            resultMap.put(Integer.toString(input.hashCode()),handle);
        }
    }
}
